using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.attachments;

namespace SupplierCustomerManagement.Write.API.Controllers
{
    /// <summary>
    /// 附件管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AttachmentsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IMapper _mapper;
        private readonly ILogger<AttachmentsController> _logger;

        public AttachmentsController(
            IMediator mediator,
            IMapper mapper,
            ILogger<AttachmentsController> logger)
        {
            _mediator = mediator;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="attachmentFile">附件文件</param>
        /// <param name="relatedEntityId">关联实体ID</param>
        /// <param name="relatedEntityType">关联实体类型</param>
        /// <param name="bucketName">存储桶名称（可选，默认为attachments）</param>
        /// <param name="prefix">文件前缀（可选，默认为files）</param>
        /// <param name="uploaderId">上传人ID（可选）</param>
        /// <param name="uploaderName">上传人姓名（可选）</param>
        /// <param name="remarks">备注（可选）</param>
        /// <returns>上传结果</returns>
        [HttpPost]
        public async Task<ApiResult<int>> UploadAttachment(
            IFormFile attachmentFile,
            int relatedEntityId,
            string? relatedEntityType=null,
            string bucketName = "attachments",
            string prefix = "files",
            int? uploaderId = null,
            string? uploaderName = null,
            string? remarks = null)
        {
            try
            {
                _logger.LogInformation("开始上传附件，文件名：{FileName}，关联实体ID：{RelatedEntityId}，关联实体类型：{RelatedEntityType}",
                    attachmentFile?.FileName, relatedEntityId, relatedEntityType);

                var command = new AddAttachmentCommand
                {
                    AttachmentFile = attachmentFile,
                    RelatedEntityId = relatedEntityId,
                    RelatedEntityType = relatedEntityType,
                    BucketName = bucketName,
                    Prefix = prefix,
                    GenerateUniqueName = true,
                    UploaderId = uploaderId,
                    UploaderName = uploaderName,
                    Remarks = remarks
                };

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("附件上传成功，ID：{AttachmentId}，文件名：{FileName}", 
                        result.data, attachmentFile?.FileName);
                }
                else
                {
                    _logger.LogWarning("附件上传失败，错误信息：{Message}，文件名：{FileName}", 
                        result.message, attachmentFile?.FileName);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "附件上传过程中发生异常，文件名：{FileName}", attachmentFile?.FileName);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"附件上传异常：{ex.Message}",
                    data = 0
                };
            }
        }

        /// <summary>
        /// 批量上传附件
        /// </summary>
        /// <param name="attachmentFiles">附件文件列表</param>
        /// <param name="relatedEntityId">关联实体ID</param>
        /// <param name="relatedEntityType">关联实体类型</param>
        /// <param name="bucketName">存储桶名称（可选，默认为attachments）</param>
        /// <param name="prefix">文件前缀（可选，默认为files）</param>
        /// <param name="uploaderId">上传人ID（可选）</param>
        /// <param name="uploaderName">上传人姓名（可选）</param>
        /// <param name="remarks">备注（可选）</param>
        /// <returns>批量上传结果</returns>
        [HttpPost("batch")]
        public async Task<ApiResult<List<int>>> BatchUploadAttachments(
            List<IFormFile> attachmentFiles,
            int relatedEntityId,
            string relatedEntityType,
            string bucketName = "attachments",
            string prefix = "files",
            int? uploaderId = null,
            string? uploaderName = null,
            string? remarks = null)
        {
            try
            {
                _logger.LogInformation("开始批量上传附件，文件数量：{FileCount}，关联实体ID：{RelatedEntityId}，关联实体类型：{RelatedEntityType}",
                    attachmentFiles?.Count, relatedEntityId, relatedEntityType);

                var uploadedIds = new List<int>();
                var errors = new List<string>();

                foreach (var file in attachmentFiles)
                {
                    try
                    {
                        var command = new AddAttachmentCommand
                        {
                            AttachmentFile = file,
                            RelatedEntityId = relatedEntityId,
                            RelatedEntityType = relatedEntityType,
                            BucketName = bucketName,
                            Prefix = prefix,
                            GenerateUniqueName = true,
                            UploaderId = uploaderId,
                            UploaderName = uploaderName,
                            Remarks = remarks
                        };

                        var result = await _mediator.Send(command);

                        if (result.code == ResultEnumCode.Ok)
                        {
                            uploadedIds.Add(result.data);
                            _logger.LogInformation("附件上传成功，ID：{AttachmentId}，文件名：{FileName}", 
                                result.data, file.FileName);
                        }
                        else
                        {
                            errors.Add($"文件 {file.FileName} 上传失败：{result.message}");
                            _logger.LogWarning("附件上传失败，错误信息：{Message}，文件名：{FileName}", 
                                result.message, file.FileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        errors.Add($"文件 {file.FileName} 上传异常：{ex.Message}");
                        _logger.LogError(ex, "附件上传过程中发生异常，文件名：{FileName}", file.FileName);
                    }
                }

                if (uploadedIds.Count > 0)
                {
                    var message = errors.Count > 0 
                        ? $"成功上传 {uploadedIds.Count} 个文件，失败 {errors.Count} 个文件" 
                        : $"成功上传 {uploadedIds.Count} 个文件";

                    return new ApiResult<List<int>>
                    {
                        code = ResultEnumCode.Ok,
                        message = message,
                        data = uploadedIds
                    };
                }
                else
                {
                    return new ApiResult<List<int>>
                    {
                        code = ResultEnumCode.fails,
                        message = $"所有文件上传失败：{string.Join("; ", errors)}",
                        data = new List<int>()
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量上传附件过程中发生异常");

                return new ApiResult<List<int>>
                {
                    code = ResultEnumCode.fails,
                    message = $"批量上传附件异常：{ex.Message}",
                    data = new List<int>()
                };
            }
        }

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="command">删除命令</param>
        /// <returns>删除结果</returns>
        [HttpDelete]
        public async Task<ApiResult<bool>> DeleteAttachment([FromBody] DeleteAttachmentCommand command)
        {
            try
            {
                _logger.LogInformation("开始删除附件，ID：{AttachmentId}，是否删除存储文件：{DeleteFromStorage}", 
                    command.Id, command.DeleteFromStorage);

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("附件删除成功，ID：{AttachmentId}", command.Id);
                }
                else
                {
                    _logger.LogWarning("附件删除失败，错误信息：{Message}，ID：{AttachmentId}", 
                        result.message, command.Id);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除附件过程中发生异常，ID：{AttachmentId}", command.Id);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"删除附件异常：{ex.Message}",
                    data = false
                };
            }
        }
    }
} 